#include "mainwindow.h"
#include <DWidgetUtil>
#include <DTitlebar>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <iostream>
#include <QTimer>
#include <QStackedLayout>
#include <DMessageManager>
#include <src/settings/settings.h>
#include <QProcess>
//#include <QScreen>
//#include <QGuiApplication>

//const QUrl MAINPAGE("https://sim.plopco.com/#/");
//const QUrl MAINPAGE = ;
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
    DBlurEffectWidget(parent)
{
//    double dpi  = QGuiApplication::primaryScreen()->logicalDotsPerInch() / 96;
    InitMainWindow();
    connect(tabbar_main,&DTabBar::currentChanged,[=](int index){
        setPageIndex(tabbar_main->tabData(index).toInt());

    });
}

MainWindow::MainWindow(QUrl url)
{
    InitMainWindow();
    if(url.isEmpty()){
        addPage(Settings::getValue("MainPageAddress"));
    }else {
        addPage(url);
    }
    connect(tabbar_main,&DTabBar::currentChanged,[=](int index){
        setPageIndex(tabbar_main->tabData(index).toInt());

    });
}

MainWindow::~MainWindow()
{
    cout<<"exit";
    settingDialog->hide();
}

void MainWindow::InitMainWindow()
{
    webwidget=new WebWidget;
    loader=new DWaterProgress;
    addressedit_main=new AddressEdit;
    tabbar_main=new DTabBar;
    searchedit=new DSearchEdit;
    mainMenu=new QMenu;
    addTab=new QAction;
    effects=new QAction;
    setting=new QAction;
    addWindow=new QAction;
    bookmark=new QMenu;
    titlebar=new DTitlebar;
    progressloader=new ProgressLoader;
    settingDialog=new SettingDialog;
    //设置窗口基本属性

    resize(1300,800);
    moveToCenter(this);
    setMinimumSize(590,350);
    w=new QWidget;
    QHBoxLayout* tmp_layout=new QHBoxLayout;
    tmp_layout->addWidget(w);
    setLayout(tmp_layout);
    tmp_layout->setMargin(0);
    //    setCentralWidget(w);
    QVBoxLayout* mainlayout=new QVBoxLayout;
    w->setLayout(mainlayout);
    mainlayout->setMargin(0);
    mainlayout->setSpacing(0);
    setWindowIcon(QIcon::fromTheme("deepin-browser"));
    addTab->setText(tr("Add Tab"));
    effects->setText(tr("Window Effect"));
    effects->setCheckable(true);
    setting->setText(tr("Settings"));
    addWindow->setText(tr("Add Window"));
    mainMenu->addAction(addTab);
    mainMenu->addAction(addWindow);
    mainMenu->addSeparator();
    mainMenu->addAction(setting);
    mainMenu->addAction(effects);
    titlebar->setMenu(mainMenu);
    connect(addTab,&QAction::triggered,this,[=](){MainWindow::addPage(Settings::getValue("MainPageAddress"));});
    connect(setting,&QAction::triggered,[=](){
        settingDialog->show();
    });
    connect(addWindow,&QAction::triggered,[=](){
        QProcess *run=new QProcess;
        run->start(QApplication::applicationFilePath().toUtf8()+" "+Settings::getValue("MainPageAddress")+" &");
    });

    connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::themeTypeChanged, this, [=](DGuiApplicationHelper::ColorType themeType) {
        QColor main_color;
        main_color=DGuiApplicationHelper::instance()->applicationPalette().highlight().color();
        if(themeType==DGuiApplicationHelper::DarkType){
            qDebug()<<"Dark";
            QPalette palette(this->palette());
            palette.setColor(QPalette::Background, QColor("#282828"));
            w->setPalette(palette);
            addressbar_main->setPalette(palette);
            btn_left->setIcon(QIcon::fromTheme("arrow-left"));
            btn_right->setIcon(QIcon::fromTheme("arrow-right"));
            btn_f5->setIcon(QIcon::fromTheme("refresh"));
            btn_bookmark->setIcon(QIcon(":/btn/icons/pushbutton/bookmark.svg"));
            MainWindow::setMaskColor(QColor(40,40,40));
            progressloader->setTheme(true,main_color);

        }else {
            qDebug()<<"Light";
            QPalette palette(this->palette());
            palette.setColor(QPalette::Background, QColor("#FFFFFF"));
            w->setPalette(palette);
            addressbar_main->setPalette(palette);
            btn_left->setIcon(QIcon::fromTheme("arrow-left-dark"));
            btn_right->setIcon(QIcon::fromTheme("arrow-right-dark"));
            btn_f5->setIcon(QIcon::fromTheme("refresh_dark"));
            btn_bookmark->setIcon(QIcon(":/btn/icons/pushbutton/bookmark_dark.svg"));
            MainWindow::setMaskColor(QColor(245,245,245));
            progressloader->setTheme(false,main_color);

        }
    });

    //定义titlebar外观
    titlebar->setSeparatorVisible(false);
    titlebar->setBackgroundTransparent(true);
    titlebar->setIcon(QIcon::fromTheme("deepin-browser"));


    //设置tabbar
    titlebar->setCustomWidget(tabbar_main);
//    setTitlebarShadowEnabled(false);
    tabbar_main->setTabsClosable(true);
    tabbar_main->setStartDragDistance(3);
    tabbar_main->setTabLabelAlignment(Qt::AlignLeft | Qt::AlignVCenter);

    connect(tabbar_main,&DTabBar::tabAddRequested,[=](){
        MainWindow::addPage(Settings::getValue("MainPageAddress"));
    });
    connect(tabbar_main,&DTabBar::tabCloseRequested,[=](int index){
        if(tabbar_main->count()==1){
            webwidget->page(tabbar_main->tabData(tabbar_main->currentIndex()).toInt())->page->setUrl(Settings::getValue("MainPageAddress"));
        }else {
            MainWindow::delPage(tabbar_main->tabData(index).toInt());
        }

    });
    connect(tabbar_main,&DTabBar::tabBarDoubleClicked,[=](int index){ //双击和点击关闭的效果是一样的
        emit tabbar_main->tabCloseRequested(index);
    });
    MainCode=0;



    //设置地址栏
    addressbar_main=new QWidget;
    addressbar_main->setFixedHeight(42);
    QHBoxLayout* addresslayout=new QHBoxLayout;
    addresslayout->setContentsMargins(12,4,12,3);
    addressbar_main->setLayout(addresslayout);
    btn_left=new DPushButton;
    btn_right=new DPushButton;
    btn_f5=new DPushButton;
    btn_bookmark=new DPushButton;
    btn_left->setFixedSize(36,36);
    btn_right->setFixedSize(36,36);
    btn_f5->setFixedSize(36,36);
    btn_bookmark->setFixedSize(36,36);
    searchedit->setFixedWidth(230);
    searchedit->hide();
    connect(btn_f5,&DPushButton::clicked,[=](){

        addressedit_main->setText(webwidget->page(tabbar_main->tabData(tabbar_main->currentIndex()).toInt())->page->url().toString());
        webwidget->page(tabbar_main->tabData(tabbar_main->currentIndex()).toInt())->page->reload();
    });
    connect(btn_left,&DPushButton::clicked,[=](){
        webwidget->page(tabbar_main->tabData(tabbar_main->currentIndex()).toInt())->page->back();
    });
    connect(btn_right,&DPushButton::clicked,[=](){
        webwidget->page(tabbar_main->tabData(tabbar_main->currentIndex()).toInt())->page->forward();
    });
    connect(addressedit_main,&AddressEdit::returnPressed,[=](){
        QUrl url(addressedit_main->text());
        if(url.scheme()=="http" || url.scheme()=="https"){
            webwidget->page(tabbar_main->tabData(tabbar_main->currentIndex()).toInt())->page->setUrl(QUrl(addressedit_main->text()));
        }else {
            webwidget->page(tabbar_main->tabData(tabbar_main->currentIndex()).toInt())->page->setUrl(QUrl("https://www.baidu.com/s?wd="+addressedit_main->text()));
        }

    });
    connect(btn_bookmark,&DPushButton::clicked,[=](){

        MainWindow::loadBookmark();
        if(bookmark->isEmpty()){
            DMessageManager::instance()->sendMessage(this, style()->standardIcon(QStyle::SP_MessageBoxWarning),
                                                     tr("The bookmark is empty!"));
        }else {
            QPoint point;
            point.setX(MainWindow::x()+btn_bookmark->x());
            point.setY(MainWindow::y()+titlebar->height()+btn_bookmark->y()+btn_bookmark->height());
            bookmark->exec(point);
        }
    });


    progressloader->setValue(20);


    addresslayout->addWidget(btn_left);
    addresslayout->addWidget(btn_right);
    addresslayout->addWidget(btn_f5);
    addresslayout->addWidget(addressedit_main);
    addresslayout->addWidget(searchedit);
    addresslayout->addWidget(btn_bookmark);


    //设置网页空间


    DBlurEffectWidget *wb=new DBlurEffectWidget;
    mainlayout->addWidget(titlebar);
    mainlayout->addWidget(addressbar_main);
    mainlayout->addWidget(progressloader);
    mainlayout->addWidget(webwidget);
    mainlayout->setAlignment(wb,Qt::AlignBottom);
    wb->setFixedHeight(100);

    //加载书签菜单
    loadBookmark();

    //链接配置
    connect(effects,&QAction::changed,[=](){
        Settings::setValue("WindowEffect",effects->isChecked()?"true":"false");
        settingDialog->appearanceSettings->btn_effect->setChecked(effects->isChecked());
        if(effects->isChecked()){
            setBlurEnabled(true);
            setMaskAlpha(settingDialog->appearanceSettings->getMask());//0-255 透明度从高到底
            QPalette plt;
            plt.setColor(QPalette::Background,QColor(255,255,255,0));
            w->setAutoFillBackground(true);
            w->setPalette(plt);
        }else {
            setBlurEnabled(false);
            w->setAutoFillBackground(true);
            if(DGuiApplicationHelper::instance()->themeType()==DGuiApplicationHelper::DarkType){
                QPalette plt;
                plt.setColor(QPalette::Background,QColor(40,40,40,255));
                w->setPalette(plt);
            }else {
                QPalette plt;
                plt.setColor(QPalette::Background,QColor(245,245,245,255));
                w->setPalette(plt);
            }
        }
    });
    connect(settingDialog,&SettingDialog::EffectChange,[=](bool open,quint8 value){
        effects->setChecked(open);
        setMaskAlpha(value);
    });
    loadConfig();
    timer=new QTimer;
    timer->setInterval(1000);
    timer->start();
    connect(timer,&QTimer::timeout,[=](){
        MainWindow::timer_1000();
    });
}

void MainWindow::updateTabWidth()
{
    int tabWidth=(tabbar_main->width()-130)/tabbar_main->count();
    tabbar_main->hide();
    for(int i=0;i<tabbar_main->count();i++){
        if(tabWidth<40){
            tabWidth=40;
        }else if(tabWidth>220){
            tabWidth=220;
        }
        tabbar_main->setTabMinimumSize(i,QSize(tabWidth,36));
        tabbar_main->setTabMaximumSize(i,QSize(tabWidth,37));
    }
    tabbar_main->hide();
    //下边这部分是因为Dtabbar中的按钮在标签尺寸变化后不会跟随移动,只有在新建或者删除标签时才会移动.
    int tmp=tabbar_main->addTab("");
    tabbar_main->setTabMinimumSize(tmp,QSize(0,36));
    tabbar_main->setTabMaximumSize(tmp,QSize(0,37));
    tabbar_main->removeTab(tmp);
    tabbar_main->show();
}
void MainWindow::resizeEvent(QResizeEvent *event){
    Q_UNUSED(event)
    updateTabWidth();
}
void MainWindow::loadConfig()
{
    //加载主窗口配置项
    //窗口特效
    if(Settings::getValue("WindowEffect")=="true"){
        effects->setChecked(true);
    }
    else{
        effects->setChecked(false);
    }
    emit effects->changed();
}

void MainWindow::timer_1000()
{
    //鼠标移除后刷新标签栏宽度
    int x=this->mapFromGlobal(QCursor().pos()).x();
    int y=this->mapFromGlobal(QCursor().pos()).y();
    if(x<0 || x>tabbar_main->width() || y<0 || y >=tabbar_main->height()){
        updateTabWidth();
    }

}
void MainWindow::addPage(QUrl url,int index)
{
    WebWidget::WebPage *p;
    p=webwidget->addpage(url);
    addPage_conf(p,index);
}
void MainWindow::addPage(WebEngineView* page,int index)
{
    WebWidget::WebPage *p;
    p=webwidget->addpage(page);
    addPage_conf(p,index);

}
//为了减少代码，将重复代码合并为
void MainWindow::addPage_conf(WebWidget::WebPage *p,int index)
{
    p->code=newCode();
    QVariant data;
    data.setValue(p->code);
    int tabbar_index;
    if(index==-1){
        tabbar_index=tabbar_main->addTab(tr("Loading..."));
    }else {
        tabbar_index=index;
        tabbar_main->insertTab(index,tr("Loading..."));
    }
    tabbar_main->setTabData(tabbar_index,data);
    tabbar_main->setTabMinimumSize(tabbar_index,QSize(220,36));
    tabbar_main->setTabMaximumSize(tabbar_index,QSize(221,37));
    connect(p->page,&QWebEngineView::titleChanged,[=](){
        if(p->page->title()==""){
            tabbar_main->setTabText(tabbarIndex(p->code),tr("Loading..."));

        }else{
            QString title=p->page->title();
            tabbar_main->setTabText(tabbarIndex(p->code),title);
        }
        if(webwidget->page(tabbar_main->tabData(tabbar_main->currentIndex()).toInt())==p){
            addressedit_main->title=p->page->title();
            MainWindow::setWindowTitle(p->page->title());
        }

    });
    connect(p->page,&QWebEngineView::iconChanged,[=](QIcon icon){
        tabbar_main->setTabIcon(tabbarIndex( p->code),icon);
    });
    connect(p->page,&QWebEngineView::urlChanged,[=](QUrl url){

        if(p->page->isNewWindow && p->page->p!=nullptr){
            switch (p->page->newWindowType) {
            case QWebEnginePage::WebBrowserTab:
                MainWindow::addPage(p->page->p,tabbar_main->currentIndex()+1);
                p->page->isNewWindow=false;
                break;
            case QWebEnginePage::WebBrowserWindow:
                QProcess *run=new QProcess;
                run->start(QApplication::applicationFilePath().toUtf8()+" "+url.toString().toUtf8()+" &");
                break;
            }

        }else {
            tabbar_main->setTabText(tabbarIndex(p->code),tr("Loading..."));
            addressedit_main->setText(webwidget->page(tabbar_main->tabData(tabbar_main->currentIndex()).toInt())->page->url().toString());
            addressedit_main->setSelection(0,0);
            addressedit_main->setStar(isStar(url));
        }
    });
    connect(p->page,&QWebEngineView::loadStarted,[=](){

    });
    connect(p->page,&QWebEngineView::loadProgress,[=](int y){
        if(MainWindow::isNowPage(p->code)){
            MainWindow::progressloader->setValue(y);

        }
    });
    connect(p->page,&QWebEngineView::loadFinished,[=](){
        if(MainWindow::isNowPage(p->code)){
            MainWindow::progressloader->setValue(0);
            addressedit_main->updateSafeState();
        }
        QString title=p->page->title();
        tabbar_main->setTabText(tabbarIndex(p->code),title);
//        if(p->page->title()==""){
//            tabbar_main->removeTab(tabbarIndex(p->code));
//        }
    });
    connect(p->page->page()->profile(),&QWebEngineProfile::downloadRequested,[=](QWebEngineDownloadItem* item){
        cout<<"Download:"<<item->url().toString().toStdString();
    });
    setPageIndex(p->code);
    updateTabWidth();
}



//查找code，删除对应的page
void MainWindow::delPage(int code)
{
    tabbar_main->removeTab(tabbarIndex(code));
    webwidget->delPage(code);

}

//设置当前的page
void MainWindow::setPageIndex(int code)
{
    tabbar_main->setCurrentIndex(tabbarIndex(code));
    webwidget->ShowPage(webwidget->page(code));
    addressedit_main->setText(webwidget->page(code)->page->url().toString());
    addressedit_main->updateSafeState();
    addressedit_main->setStar(isStar(webwidget->page(tabbar_main->tabData(tabbar_main->currentIndex()).toInt())->page->url()));
    addressedit_main->title=webwidget->page(code)->page->title();
    progressloader->setValue(0);
    setWindowTitle(webwidget->page(code)->page->title());
    if(tabbar_main->count()>1){
        setWindowTitle(QString(tr("%1 tab pages")).arg(tabbar_main->count()));
    }
}

bool MainWindow::isNowPage(int code)
{
    return(tabbarIndex(code)==tabbar_main->currentIndex());
}
//给page申请一个新的编号
int MainWindow::newCode()
{
    bool isHave;
    int code=++MainCode;
    do{
        isHave=false;
        for (int i=0;i<tabbar_main->count();i++) {
            if(tabbar_main->tabData(i).toInt()==code){
                isHave=true;
                code++;
                break;
            }
        }
    }while(isHave);
    return code;

}
//给出page编号，返回对应的标签index
int MainWindow::tabbarIndex(int code)
{
    for (int i=0;i<tabbar_main->count();i++) {
        if(tabbar_main->tabData(i).toInt()==code){
            return i;
        }
    }
    return -1;
}

void MainWindow::addBookmark(QString title,QUrl url)
{
    QAction *tag=new QAction;
    tag->setText(title);
    QVariant data;
    data.setValue(url);
    tag->setData(data);
    bookmark->addAction(tag);
}

void MainWindow::loadBookmark()
{
    bookmark->clear();

    QFile jsonFile(setting_path+"bookmark.json");
    jsonFile.open(QFile::ReadOnly);
    const QByteArray bty = jsonFile.readAll();
    addressedit_main->json_bookmark=QJsonDocument::fromJson(bty).object();
    QJsonArray array=addressedit_main->json_bookmark.value("bookmarkList").toArray();
    for (int i=0;i<array.size();i++) {
        QAction *newAction=new QAction;
        newAction->setText(array[i].toObject().value("name").toString());
        newAction->setData(array[i].toObject().value("url").toString());
        bookmark->addAction(newAction);
        connect(newAction,&QAction::triggered,[=](){MainWindow::addPage(newAction->data().toUrl());});
        newAction->deleteLater();
    }
}

bool MainWindow::isStar(QUrl url)
{
    QJsonArray array=addressedit_main->json_bookmark.value("bookmarkList").toArray();
    for (int i=0;i<array.size();i++) {
        if(url.toString()==array[i].toObject().value("url").toString()){
            return true;

        }
    }
    return false;
}
